package cn.wj.school.app.ui.controller;

import cn.wj.school.app.dto.LoginReqMsg;
import cn.wj.school.app.enums.SessionFactory;
import cn.wj.school.app.ui.view.StageView;
import cn.wj.school.common.controller.ControlledStage;
import cn.wj.school.common.controller.StageController;
import cn.wj.school.common.enums.UiFactory;
import cn.wj.school.common.utils.I18nUtils;
import javafx.beans.binding.Bindings;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;

import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;

public class LoginController implements ControlledStage, Initializable {

    @FXML
    private Button login;
    @FXML
    private TextField userNameFiled;
    @FXML
    private PasswordField passwordFiled;
    @FXML
    private ProgressBar loginProgress;
    @FXML
    private Pane errorPane;
    @FXML
    private Label errorTips;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        // 验证规则： userId非空且为数字 password非空
        login.disableProperty()
                .bind(Bindings.createBooleanBinding(
                        () -> userNameFiled.getText().length() == 0 || passwordFiled.getText().length() == 0,
                        userNameFiled.textProperty(), passwordFiled.textProperty()));
    }


    /**
     * 登录
     * 
     * @throws IOException
     */
    public void toLogin() throws IOException {

        String userName = userNameFiled.getText();
        String password = passwordFiled.getText();

        if (!SessionFactory.INSTANCE.isConnectedSever()) {
            errorPane.setVisible(true);
            errorTips.setText(I18nUtils.get("login.failToConnect"));
            return;
        }
        //loginProgress.setVisible(true);
        login.setVisible(false);
        LoginReqMsg loginReq = new LoginReqMsg();
        loginReq.setPassword(password);
        loginReq.setUserName(userName);
        if (SessionFactory.INSTANCE.isConnectedSever()) {
            SessionFactory.INSTANCE.sendServerRequest(loginReq);
        }
    }


    public void backToLogin() {
        loginProgress.setVisible(false);
        errorPane.setVisible(false);
        login.setVisible(true);
    }


    public void loginEnter() {
        login.setStyle("-fx-background-radius:4;-fx-background-color: #097299");
    }

    public void loginExit() {
        login.setStyle("-fx-background-radius:4;-fx-background-color: #09A3DC");
    }


    @Override
    public Stage getMyStage() {
        StageController stageController = UiFactory.INSTANCE.getStageController();
        return stageController.getStageBy(StageView.id.LOGIN_VIEW);
    }
}
